package com.xbongbong.workflow.service.strategy.data.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.FundAccountFlowTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.TaskTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.FundAccountEntity;
import com.xbongbong.saas.domain.entity.FundAccountFlowEntity;
import com.xbongbong.saas.domain.entity.FundTransferEntity;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.FundTransferEnum;
import com.xbongbong.saas.model.FundAccountFlowModel;
import com.xbongbong.saas.model.FundAccountModel;
import com.xbongbong.saas.model.FundTransferModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.User;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.service.strategy.data.AbstractWorkflowDataStrategy;
import com.xbongbong.workflow.service.strategy.data.WorkflowDataProcessStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 资金调拨单
 * @author 魏荣杰
 *
 */
@Service
@Slf4j
public class WorkflowFundTransferStrategy extends AbstractWorkflowDataStrategy implements WorkflowDataProcessStrategy {

    @Resource
    private FundAccountFlowModel fundAccountFlowModel;
    @Resource
    private FundAccountModel fundAccountModel;
    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;
    @Resource
    private FundTransferModel fundTransferModel;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;

    @Override
    public List<Integer> type() {
        return Collections.singletonList(XbbRefTypeEnum.FUND_TRANSFER.getCode());
    }

    @Override
    public void save(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);

        String corpid = workflowTransferPOJO.getCorpid();
        Data pojoData = workflowTransferPOJO.getData();
        JSONObject data = pojoData.getData();
        Long dataId = pojoData.getId();
        User user = workflowTransferPOJO.getUser();

        long nowTime = DateTimeUtil.getInt();
        String outAccountStr = data.getString(FundTransferEnum.OUT_FUND_ACCOUNT.getAttr());
        String inAccountStr = data.getString(FundTransferEnum.IN_FUND_ACCOUNT.getAttr());
        Long transferTime = data.getLong(FundTransferEnum.TRANSFER_TIME.getAttr());
        BigDecimal amount = data.getBigDecimal(FundTransferEnum.AMOUNT.getAttr());
        List<FundAccountFlowEntity> fundAccountFlowEntityList = new ArrayList<>();
        FundAccountFlowEntity outFundAccountFlowEntity = new FundAccountFlowEntity(corpid, nowTime, user.getUserId(), FundAccountFlowTypeEnum.FUND_TRANSFER_OUT.getCode(), dataId, Long.parseLong(outAccountStr), transferTime, -amount.doubleValue());
        FundAccountFlowEntity inFundAccountFlowEntity = new FundAccountFlowEntity(corpid, nowTime, user.getUserId(), FundAccountFlowTypeEnum.FUND_TRANSFER_IN.getCode(), dataId, Long.parseLong(inAccountStr), transferTime, amount.doubleValue());
        fundAccountFlowEntityList.add(outFundAccountFlowEntity);
        fundAccountFlowEntityList.add(inFundAccountFlowEntity);
        fundAccountFlowModel.insertBatch(fundAccountFlowEntityList);
        //更新操作-转出账户
        FundAccountEntity fundAccountEntityOut = fundAccountModel.getByIdCorpid(Long.parseLong(outAccountStr), corpid);
        fundAccountEntityOut.setAmount(new BigDecimal(BasicConstant.ZERO_DOUBLE).subtract(amount));
        //更新操作-转入账户
        FundAccountEntity fundAccountEntityIn = fundAccountModel.getByIdCorpid(Long.parseLong(inAccountStr), corpid);
        fundAccountEntityIn.setAmount(amount);
        List<FundAccountEntity> updateFundAccountList = new ArrayList<>();
        updateFundAccountList.add(fundAccountEntityOut);
        updateFundAccountList.add(fundAccountEntityIn);
        fundAccountModel.updateBatchAmount(updateFundAccountList);
        addLinkDataDynamic(workflowTransferPOJO);
        // log
        afterSaveLog(workflowTransferPOJO);
    }

    @Override
    public void update(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // log
        afterUpdateLog(workflowTransferPOJO);
    }

    @Override
    public void updateBack(Long taskId, WorkflowTransferPOJO workflowTransferPOJO) throws XbbException {
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Long backupDataId = workflowTransferPOJO.getBackupDataId();
            Long dataId = workflowTransferPOJO.getData().getId();
            WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(backupDataId, corpid);
            if (Objects.nonNull(workflowBackupDataEntity)) {
                JSONObject data = workflowBackupDataEntity.getData();

                replenishAttrForBackupData(workflowTransferPOJO.getData().getData(), data);

                FundTransferEntity fundTransferEntity = new FundTransferEntity();
                fundTransferEntity.setId(dataId);
                fundTransferEntity.setCorpid(corpid);
                fundTransferEntity.setData(data);
                fundTransferEntity.setSerialNo(data.getString(FieldTypeEnum.SERIALNO.getAlias()));
                fundTransferEntity.setOwnerId(getOwnerId(data));
                fundTransferEntity.setDepartmentId(data.getLong(FieldTypeEnum.DEPARTMENTID.getAlias()));
                FormDataUtil.removeSystemData(data);
                if (Objects.equals(workflowTransferPOJO.getOperate(), WorkflowOperateEnum.UPDATE.getType())) {
                    fundTransferEntity.setFlowStatus(FlowStatusEnum.PASS.getType());
                }
                fundTransferModel.update(fundTransferEntity);

                // 回退被删掉的子表单
                updateBackSubForm(fundTransferEntity, corpid, IndexTypeEnum.IDX_SAAS_FUND_TRANSFER_SUB);
                //回退被删掉的富文本
                updateBackRichText(taskId, workflowTransferPOJO);
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowFundTransferStrategy.updateBack error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public void approvalFailed(Long taskId, WorkflowTransferPOJO workflowTransferPOJO, Integer taskType) throws XbbException {
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Data workflowData = workflowTransferPOJO.getData();
            Long dataId = workflowData.getId();
            Long formId = workflowData.getFormId();
            Integer businessType = workflowData.getBusinessType();
            Integer saasMark = workflowData.getSaasMark();
            FundTransferEntity fundTransferEntity = new FundTransferEntity();
            fundTransferEntity.setId(dataId);
            if (Objects.equals(TaskTypeEnum.REVOKE.getType(), taskType)) {
                fundTransferEntity.setFlowStatus(FlowStatusEnum.REVOKE.getType());
            } else {
                fundTransferEntity.setFlowStatus(FlowStatusEnum.REJECT.getType());
            }
            fundTransferEntity.setCorpid(corpid);
            fundTransferEntity.setUpdateTime(DateTimeUtil.getInt());
            fundTransferModel.update(fundTransferEntity);
            // 子表单
            DelEnum del = DelEnum.APPROVE_FAILED;

            paasFormSubDataModel.deleteBatchByDataId(Collections.singletonList(dataId), corpid, IndexTypeEnum.IDX_SAAS_FUND_TRANSFER_SUB, del);
            //富文本
            deleteFormRichText(dataId, corpid, formId, businessType, saasMark, DelEnum.NORMAL);
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowFundTransferStrategy.approvalFailed error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }
}
